package com.netty.client.socket;

import com.netty.model.SentBody;
import com.netty.model.proto.SentBodyProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author zl
 * @version 1.0
 * @date 2021/9/24 16:17
 */
public class SocketClientHandler extends SimpleChannelInboundHandler<SentBodyProto.Model> {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private ImSocketClientHandler imSocketClientHandler;

    public SocketClientHandler(ImSocketClientHandler imSocketClientHandler) {
        this.imSocketClientHandler = imSocketClientHandler;
    }

    //客户端去和服务端连接成功时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel链接成功<<<<<<<<<<<<<<<<<<<<<<");
        imSocketClientHandler.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel注册了<<<<<<<<<<<<<<<<<<<<<<");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel移除了<<<<<<<<<<<<<<<<<<<<<<");
        imSocketClientHandler.channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>channel 捕获到异常了，关闭了{}<<<<<<<<<<<<<<<<<<<<<<", cause);
        super.exceptionCaught(ctx, cause);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, SentBodyProto.Model model) throws Exception {
        SentBodyProto.Model message = model;
        SentBody sentBody = new SentBody();
        sentBody.setKey(message.getKey());
        sentBody.setTimestamp(message.getTimestamp());
        sentBody.putAll(message.getDataMap());
        imSocketClientHandler.channelRead0(channelHandlerContext.channel(), sentBody);
    }
}
